﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace JsiCommon.javaScriptInterop
{
    public static class JsiExpressionHelper
    {
        /// <summary>
        /// Joins expressions with chosen separator into provided builder
        /// </summary>
        public static void StringBuilderJoin(StringBuilder builder, string sep, IEnumerable<IJsiExpression> en)
        {
            StringBuilderJoin(builder, sep, from x in en select new Action<StringBuilder>(x.Compile));
        }

        /// <summary>
        /// Joins enumerable of actions with chosen separator into provided builder. Function calls each action, pass provided stringbuilder to it, and then append separator after each call. It also removes last separator from builder
        /// </summary>
        private static void StringBuilderJoin(StringBuilder builder, string sep, IEnumerable<Action<StringBuilder>> en)
        {
            var isEmpty = true;
            foreach (var action in en)
            {
                isEmpty = false;
                action(builder);
                builder.Append(sep);
            }
            if (!isEmpty)
                builder.Remove(builder.Length - 1, 1);
        }
    }
}